#include "Simulation.h"

#include "GlobalConst.h"

CSimulation * CSimulation::_Instance = NULL;

CSimulation::CSimulation() :
  m_Hge(hgeCreate(HGE_VERSION)),
  m_HgeResourceManager(NULL),
  m_Grid(NULL)
{
}

CSimulation::~CSimulation()
{
  m_Hge->Release();
  delete m_Hge;
  delete m_HgeResourceManager;
  delete m_Grid;
  if (_Instance != NULL)
  {
    delete _Instance;
  }
}

CSimulation * CSimulation::GetInstance()
{
  if (_Instance == NULL)
    _Instance = new CSimulation();

  return _Instance;
}

void CSimulation::Run()
{
  HGE  * hge  = GetInstance()->m_Hge;
  CSimulation * Simulation = GetInstance();

  hge->System_SetState(HGE_FRAMEFUNC, FrameFunction);
  hge->System_SetState(HGE_RENDERFUNC, RenderFunction);
  hge->System_SetState(HGE_FPS, 100);
  hge->System_SetState(HGE_SHOWSPLASH, false);
  hge->System_SetState(HGE_WINDOWED,   true);
  hge->System_SetState(HGE_HIDEMOUSE,  false);
  hge->System_SetState(HGE_SCREENWIDTH,  SCREEN_WIDTH);
  hge->System_SetState(HGE_SCREENHEIGHT, SCREEN_HEIGHT);
  hge->System_SetState(HGE_SCREENBPP, 32);
  hge->System_SetState(HGE_TITLE, WINDOW_TITLE);

  if (hge->System_Initiate())
  {
		hge->Resource_AttachPack("data");
		
    GetInstance()->m_HgeResourceManager = new hgeResourceManager("resources.res");
		GetInstance()->m_HgeResourceManager->Precache();
    GetInstance()->m_Grid = new CGrid;

    hge->System_Start();
  }
  else
    MessageBox(NULL, hge->System_GetErrorMessage(), "Error", MB_OK | MB_ICONERROR | MB_APPLMODAL);

  hge->System_Shutdown();
  hge->Release();
}

bool CSimulation::FrameFunction()
{
  HGE * hge = GetInstance()->m_Hge;
  
  if (hge->Input_GetKeyState(HGEK_ESCAPE))
    return true;

  return false;
}

bool CSimulation::RenderFunction()
{
  HGE * hge    = GetInstance()->m_Hge;

  hge->Gfx_BeginScene();
  hge->Gfx_Clear(0);

  CGrid * Grid = GetInstance()->m_Grid;
  Grid->Render();

  hge->Gfx_EndScene();

  return false;
}
